<template>
  <div class="wrap">
    <div class="table">
      <el-table
        :row-key="getRowKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55"
        />
        <el-table-column prop="id" label="id" width="50" />
        <el-table-column prop="title" label="标题" width="350" />
      </el-table>
      <el-pagination
        class="page"
        :page-size="3"
        @current-change="handleCurrentChange"
        background
        layout="prev, pager, next"
        :total="total"
      />
    </div>
    <ul>
      <li v-for="item in multipleSelection" :key="item.id" @click="del(item)">
        <span>{{ item.id }}---</span>
        <span>{{ item.title }}</span>
        <span class="del">删除</span>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      tableData: [],
      multipleSelection: [], // 右侧显示的选中列表
      page: 1,
      total: 0,
    };
  },
  created() {
    this.get_data();
  },
  methods: {
    // 获取数据
    async get_data() {
      const params = {
        keyword: "",
        field: "",
        page: this.page,
        page_size: 3,
      };
      const {
        data: {
          data: { data, total },
        },
      } = await axios.get("video/video_list", { params });
      this.tableData = data;
      this.total = total;

      // 在切换分页后，恢复表格的选中状态
      this.$nextTick(() => {
        this.restoreSelection();
      });
    },

    // 恢复当前分页的选中状态
    restoreSelection() {
      this.tableData.forEach((row) => {
        if (this.multipleSelection.some((item) => item.id === row.id)) {
          this.$refs.multipleTable.toggleRowSelection(row, true);
        } else {
          this.$refs.multipleTable.toggleRowSelection(row, false);
        }
      });
    },
    // 删除右侧选中列表中的项，并取消表格中的选中状态
    del(row) {
      // 找到该行的数据
      const selectedRow = this.tableData.find((item) => item.id === row.id);

      if (selectedRow) {
        // 取消选中表格行
        this.$refs.multipleTable.toggleRowSelection(selectedRow, false);
      }

      // 从 multipleSelection 中移除
      this.multipleSelection = this.multipleSelection.filter(
        (item) => item.id !== row.id
      );
    },

    // 切换分页事件
    handleCurrentChange(val) {
      this.page = val;
      this.get_data();
    },

    // 当 table 选择项发生变化时触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 获取每行的唯一 key
    getRowKey(row) {
      return row.id;
    },
  },
};
</script>

<style scoped>
.wrap {
  padding: 30px;
  display: flex;
  justify-content: flex-start;
}
.table {
  margin-right: 20px;
  width: 200px !important;
}
.page {
  margin-top: 30px;
}
.del {
  margin-left: 30px;
  color: red;
  cursor: pointer;
}
</style>
